import { defineStore } from "pinia";
import { getProducts, IProduct } from "../api/shop";
export const useProductStore = defineStore("products", {
  state: () => {
    return {
      // 类型断言
      all: [] as IProduct[], //所有商品列表
    };
  },
  getters: {},
  actions: {
    async getDataAll() {
      //异步获取商品列表
      const ret = await getProducts();
      this.all = ret;
    },
    // 购物车加1   商品减1
    decrementProduct(product: IProduct) {
      const ret = this.all.find((item) => item.id === product.id);
      if (ret) {
        ret.inventory--;
      }
    },
    addProduct(num: number, id: number) {
      const ret = this.all.find((item) => item.id === id);
      if (ret) {
        ret.inventory += num;
      }
    },
  },
});
